<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model="form"
      :defaults.sync="defaults"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.equipmentLedger_add" @click="addBtn">新 增</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.equipmentLedger_delete" @click="handleDelete">删 除</el-button>
        <el-button type="warning" size="small" icon="el-icon-download" @click="openExport">导 出</el-button>
      </template>
      <!-- <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template> -->
      <template slot-scope="{ row }" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" v-if="permission.equipmentLedger_view" @click="rowView(row)">详情</el-button>
        <el-button icon="el-icon-edit" size="small" type="text" v-if="permission.equipmentLedger_edit" @click="rowUpdate(row)">编辑</el-button>
      </template>
    </avue-crud>
    <!-- 新增 详情-->
    <el-dialog ref="dialog" :title="dialogTitle" append-to-body :visible.sync="showDialog" :close-on-click-modal="false" top="5vh" @close="closeDialog">
      <div class="sail-header-dialog-content">
        <avue-form ref="ledgerProperties" v-if="showDialog" v-model="form" :option="dialogOption">
          <template slot="EQUIPMENT_PICTURE">
            <div v-if="dialogTitle != '详情' && form.EQUIPMENT_PICTURE">
              <el-upload
                class="upload-demo"
                action="/api/blade-resource/oss/endpoint/put-file-attach"
                list-type="picture"
                accept="image/png, image/jpeg, image/jpg"
                :on-change="changeFile"
                :headers="headersObj"
                :on-preview="handlePreview"
                :before-upload="pictureUploadBefore"
                :on-success="pictureUploadSuccess"
                :file-list="pictureList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传png/jpeg/jpg文件</div>
              </el-upload>
            </div>
            <div v-if="dialogTitle === '详情' && JSON.stringify(form.EQUIPMENT_PICTURE) != '[]'">
              <el-image
                style="width: 100px; height: 100px; padding-right: 10px; display: block"
                :src="form.EQUIPMENT_PICTURE"
                @click="openPreview(0, form.EQUIPMENT_PICTURE)"
              ></el-image>
              <el-button type="text" icon="el-icon-download" size="small" @click="handleDownload(form.EQUIPMENT_PICTURE)">下载</el-button>
            </div>
          </template>
          <template slot="ACCEPTANCE_REPORT">
            <div v-if="dialogTitle != '详情' && form.ACCEPTANCE_REPORT">
              <el-upload
                class="upload-demo"
                action="/api/blade-resource/oss/endpoint/put-file-attach"
                list-type="text"
                accept=".doc,.docx,.pdf"
                :on-change="changeFile"
                :headers="headersObj"
                :before-upload="textUploadBefore"
                :on-success="inspectionUploadSuccess"
                :file-list="inspectionList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传doc/docx/pdf文件</div>
              </el-upload>
            </div>
            <div v-if="dialogTitle === '详情' && JSON.stringify(form.ACCEPTANCE_REPORT) != '[]'">
              <div>{{ form.INSPECTIONNAME }}</div>
              <el-button type="text" icon="el-icon-download" size="small" @click="handleDownload(form.ACCEPTANCE_REPORT)">下载</el-button>
            </div>
          </template>
          <template slot="PRODUCTION_VALIDATION">
            <div v-if="dialogTitle != '详情' && form.PRODUCTION_VALIDATION">
              <el-upload
                class="upload-demo"
                action="/api/blade-resource/oss/endpoint/put-file-attach"
                list-type="text"
                accept=".doc,.docx,.pdf"
                :on-change="changeFile"
                :headers="headersObj"
                :before-upload="textUploadBefore"
                :on-success="certUploadSuccess"
                :file-list="certList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传doc/docx/pdf文件</div>
              </el-upload>
            </div>
            <div v-if="dialogTitle === '详情' && JSON.stringify(form.PRODUCTION_VALIDATION) != '[]'">
              <div>{{ form.CERTNAME }}</div>
              <el-button type="text" icon="el-icon-download" size="small" @click="handleDownload(form.PRODUCTION_VALIDATION)">下载</el-button>
            </div>
          </template>
        </avue-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="dialogTitle === '新增'" type="primary" size="small" @click="submit" v-preventReClick>
          <i class="el-icon-circle-plus-outline"></i><span>保 存</span>
        </el-button>
        <el-button v-if="dialogTitle === '编辑'" type="primary" size="small" @click="submit" v-preventReClick>
          <i class="el-icon-circle-check"></i><span>修 改</span>
        </el-button>
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" @newKey="newKey"></common-modal-template>
    <export-comp ref="exportComp" page-api-url="mes-product/ems-equipment/page" :option="exportOption" :page="page" :query="query" file-name="设备台账"></export-comp>
  </basic-container>
</template>
<script>
import { getList, equipmentRecord, getDetail, add, remove, inspectionDetail, repairDetail, equipmentRepairRecord } from '@/api/equipment-manage/equipmentLedger';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import website from '@/config/website';
import exportComp from '@/components/export-comp';
import { Base64 } from 'js-base64';
import { getToken } from '@/util/auth';
import userTableConfig from '@/components/user-table-config';
import equipmentLedgerMixin from './mixins/equipmentLedgerMixin';
export default {
  name: 'EquipmentLedger',
  components: {
    CommonModalTemplate,
    exportComp,
    userTableConfig
  },
  mixins: [equipmentLedgerMixin],
  data() {
    return {
      pageCode: 'EQUIPMENT_LEDGER',
      form: {},
      defaults: {},
      query: {},
      loading: true,
      leftLoading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      tabsObj: {
        1: 'ACCEPTANCE_REPORT',
        2: 'CURING',
        3: 'CHECK',
        4: 'REPAIR'
      },
      tabsDetailObj: {
        1: 'INSPECTION_DETAIL',
        2: 'CURING_DETAIL',
        3: 'CHECK_DETAIL',
        4: 'REPAIR_DETAIL'
      },
      selectionList: [],
      dialogTitle: '新增',
      showDialog: false,
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      data: [],
      pictureList: [],
      inspectionList: [],
      certList: [],
      exportOption: {}
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.equipmentLedger_add, false),
        viewBtn: this.vaildData(this.permission.equipmentLedger_view, false),
        delBtn: this.vaildData(this.permission.equipmentLedger_delete, false),
        editBtn: this.vaildData(this.permission.equipmentLedger_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    headersObj() {
      let header = { Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}` };
      header['Blade-Auth'] = 'bearer ' + getToken();
      return header;
    },
    isDisable() {
      return this.dialogTitle === '详情';
    }
  },
  methods: {
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      // for (let i = 0; i < this.selectionList.length; i++) {
      //   if (this.selectionList[i].status === 1) {
      //     this.$message({
      //       type: 'warning',
      //       message: `编码为${this.selectionList[i].code}的设备状态正常，不可删除！`
      //     });
      //     return;
      //   }
      //   if (this.selectionList[i].status === 4) {
      //     this.$message({
      //       type: 'warning',
      //       message: `编码为${this.selectionList[i].code}的设备状态在运行中，不可删除！`
      //     });
      //     return;
      //   }
      //   if (this.selectionList[i].status === 6) {
      //     this.$message({
      //       type: 'warning',
      //       message: `编码为${this.selectionList[i].code}的设备状态在禁用中，不可删除！`
      //     });
      //     return;
      //   }
      //   if (this.selectionList[i].status === 8) {
      //     this.$message({
      //       type: 'warning',
      //       message: `编码为${this.selectionList[i].code}的设备状态在停机中，不可删除！`
      //     });
      //     return;
      //   }
      //   if (this.selectionList[i].status === 9) {
      //     this.$message({
      //       type: 'warning',
      //       message: `编码为${this.selectionList[i].code}的设备状态异常，不可删除！`
      //     });
      //     return;
      //   }
      // }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if (!params.type) {
        params.type = 'MACHINE,PRINTER';
      }
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this._forEach(this.data, (item) => {
          item.status = String(item.status);
        });
        this.loading = false;
        this.selectionClear();
      });
    },

    onDetailLoad(page, params = {}) {
      this.detailLoading = true;
      params.equipmentCode = this.form.code;
      if (this.tabsIndex !== '4') {
        let planType = {
          1: 'POINT_CHECK_PLAN',
          2: 'VERIFY_CHECK_PLAN',
          3: 'MAINTAIN_PLAN'
        };
        params.planType = planType[this.tabsIndex];
        equipmentRecord(page.currentPage, page.pageSize, Object.assign(params)).then((res) => {
          const data = res.data.data;
          this.detailPage.total = data.total;
          this.detailData = data.records;
          this.detailLoading = false;
        });
      } else {
        equipmentRepairRecord(page.currentPage, page.pageSize, Object.assign(params)).then((res) => {
          const data = res.data.data;
          this.detailPage.total = data.total;
          this.detailData = data.records;
          this.detailLoading = false;
        });
      }
    },
    addBtn() {
      this.showDialog = true;
      this.dialogOption.detail = false;
      this.dialogTitle = '新增';
    },
    findNode(list = [], prop) {
      let node;
      console.log(list, 444);
      list.forEach((ele) => {
        console.log(ele, '2222');
        if (ele.prop === prop) node = ele;
      });
      return node;
    },
    restForm() {},
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'cateGoryModal':
          this.form.categoryId = this._get(rowData, 'id', '');
          this.form.categoryName = this._get(rowData, 'name', '');
          break;
        case 'principalModal':
          this.form.principal = this._get(rowData, 'id', '');
          this.form.principalName = this._get(rowData, 'realName', '');
          break;
        case 'vendorModal':
          this.form.vendorId = this._get(rowData, 'id', '');
          this.form.vendorName = this._get(rowData, 'name', '');
          this.form.vendorCode = this._get(rowData, 'partnerNo', '');
          break;
        case 'workshopModal':
          this.form.workshopId = this._get(rowData, 'id', '');
          this.form.workshopName = this._get(rowData, 'name', '');
          this.form.lineId = '';
          this.form.lineName = '';
          break;
        case 'lineModal':
          this.form.lineId = this._get(rowData, 'id', '');
          this.form.lineName = this._get(rowData, 'name', '');
          break;
        default:
          break;
      }
    },
    pictureUploadSuccess(res) {
      if (this.form.attachmentList) {
        for (let i = 0; i < this.form.attachmentList.length; i++) {
          if ('EQUIPMENT_PICTURE' === this.form.attachmentList[i].type) {
            this.form.attachmentList.splice(i, 1);
          }
        }
      } else {
        this.form.attachmentList = [];
      }
      this.form.EQUIPMENT_PICTURE = res.data.link;
      this.form['attachmentList'].push({
        attachmentId: res.data.attachId,
        link: res.data.link,
        attachmentName: res.data.originalName,
        type: 'EQUIPMENT_PICTURE'
      });
      console.log(this.pictureList, ' this.pictureList');
    },
    inspectionUploadSuccess(res) {
      if (this.form.attachmentList) {
        for (let i = 0; i < this.form.attachmentList.length; i++) {
          if ('ACCEPTANCE_REPORT' === this.form.attachmentList[i].type) {
            this.form.attachmentList.splice(i, 1);
          }
        }
      } else {
        this.form.attachmentList = [];
      }
      this.form.ACCEPTANCE_REPORT = res.data.link;
      this.form['attachmentList'].push({
        attachmentId: res.data.attachId,
        link: res.data.link,
        attachmentName: res.data.originalName,
        type: 'ACCEPTANCE_REPORT'
      });
    },
    certUploadSuccess(res) {
      if (this.form.attachmentList) {
        for (let i = 0; i < this.form.attachmentList.length; i++) {
          if ('PRODUCTION_VALIDATION' === this.form.attachmentList[i].type) {
            this.form.attachmentList.splice(i, 1);
          }
        }
      } else {
        this.form.attachmentList = [];
      }
      this.form.PRODUCTION_VALIDATION = res.data.link;
      this.form['attachmentList'].push({
        attachmentId: res.data.attachId,
        link: res.data.link,
        attachmentName: res.data.originalName,
        type: 'PRODUCTION_VALIDATION'
      });
    },

    changeFile(files, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
    },
    /**
     * 上传前方法
     */
    pictureUploadBefore(file) {
      console.log(file);
      if (file.name.split('.')[1] != 'png' && file.name.split('.')[1] != 'jpeg' && file.name.split('.')[1] != 'jpg') {
        this.$message({
          type: 'warning',
          message: '只能上传png/jpeg/jpg文件！'
        });
        return false;
      }
    },
    textUploadBefore(file) {
      if (file.name.split('.')[1] != 'doc' && file.name.split('.')[1] != 'docx' && file.name.split('.')[1] != 'pdf') {
        this.$message({
          type: 'warning',
          message: '只能上传dox/docx/pdf文件！'
        });
        return false;
      }
    },
    /**
     * 提交
     */
    async submit() {
      delete this.form.EQUIPMENT_PICTURE;
      delete this.form.ACCEPTANCE_REPORT;
      delete this.form.PRODUCTION_VALIDATION;
      this.form.equipmentType = 'MACHINE';
      this.$refs.ledgerProperties.validate((valid, done) => {
        if (valid) {
          add(this.form).then((res) => {
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: res.data.msg
            });
            this.showDialog = false;
          });
        }
        done();
      });
    },
    /**
     * 查看详情数据
     */
    rowView(row) {
      this.showDialog = true;
      this.dialogOption.detail = true;
      this.dialogTitle = '详情';
      getDetail(row.id).then((res) => {
        let data = res.data.data;
        this.handleDetailData(data);
      });
    },
    rowUpdate(row) {
      this.showDialog = true;
      this.dialogOption.detail = false;
      this.dialogTitle = '编辑';
      row.options = JSON.stringify({ version: row.version });
      getDetail(row.id).then((res) => {
        let data = res.data.data;
        this.handleDetailData(data);
      });
    },
    handleDetailData(data) {
      this.form = data;
      this.form.suitPartName = String(this._map(data.equipmentPartList || [], (item) => item.partName));
      data.attachmentList = this._map(data.attachmentList || [], (item) => {
        return {
          ...item,
          name: item.attachmentName,
          url: item.link
        };
      });
      this.pictureList = this._filter(data.attachmentList || [], (item) => item.type === 'EQUIPMENT_PICTURE');
      this.inspectionList = this._filter(data.attachmentList || [], (item) => item.type === 'ACCEPTANCE_REPORT');
      this.certList = this._filter(data.attachmentList || [], (item) => item.type === 'PRODUCTION_VALIDATION');
      this._forEach(data.attachmentList, (item) => {
        if (item.type === 'EQUIPMENT_PICTURE') {
          this.form.EQUIPMENT_PICTURE = item.link;
        } else if (item.type === 'ACCEPTANCE_REPORT') {
          this.form.ACCEPTANCE_REPORT = item.link;
          this.form.INSPECTIONNAME = item.attachmentName;
        } else if (item.type === 'PRODUCTION_VALIDATION') {
          this.form.PRODUCTION_VALIDATION = item.link;
          this.form.CERTNAME = item.attachmentName;
        }
      });
      this._forEach(data.equipmentCheckRecordVOList || [], (item) => {
        if (item.planType === 'VERIFY_CHECK_PLAN') {
          this.form.verifyNextCheckDate = item.nextCheckDate || '';
          this.form.verifyLastNextCheckDate = item.lastCheckDate || '';
        } else if (item.planType === 'MAINTAIN_PLAN') {
          this.form.maintainNextCheckDate = item.nextCheckDate || '';
          this.form.maintainLastNextCheckDate = item.lastCheckDate || '';
        } else if (item.planType === 'POINT_CHECK_PLAN') {
          this.form.pointNextCheckDate = item.nextCheckDate || '';
          this.form.pointLastNextCheckDate = item.lastCheckDate || '';
        }
      });
    },
    closeDialog() {
      this.form = {};
      this.pictureList = [];
      this.inspectionList = [];
      this.certList = [];
    },
    handleDownload(link) {
      window.open(`${link}`);
    },
    openPreview(index = 0, link) {
      this.$ImagePreview([{ url: link }], index, {
        closeOnClickModal: false
      });
    },
    getValidResult(label, value) {
      switch (label) {
        case 'ip':
          let arr = value.split('.');
          arr[0] = Number(arr[0]);
          arr[1] = Number(arr[1]);
          arr[2] = Number(arr[2]);
          arr[3] = Number(arr[3]);
          if (arr.length < 4 || arr.length > 4) {
            return false;
          } else {
            let reg = /^(0|\+?[1-9][0-9]*)$/;
            if (reg.test(arr[0]) && reg.test(arr[1]) && reg.test(arr[2]) && reg.test(arr[3])) {
              if (arr[0] > 255 || arr[1] > 255 || arr[2] > 255 || arr[3] > 255) {
                return false;
              } else {
                return true;
              }
            } else {
              return false;
            }
          }
        case 'port':
          let reg = /^(0|\+?[1-9][0-9]*)$/;
          if (reg.test(Number(value))) {
            if (Number(value) > 65535) {
              return false;
            } else {
              return true;
            }
          } else {
            return false;
          }
      }
    },
    openExport() {
      this.$refs.exportComp.visible = true;
      console.log(this.option);
      this.exportOption = this._cloneDeep(this.option);
      console.log(this.exportOption);
      this.exportOption.column = [
        {
          label: '设备编码',
          prop: 'code'
        },
        {
          label: '设备名称',
          prop: 'name'
        },
        {
          label: '设备类型',
          prop: 'type',
          type: 'select',
          dicData: [
            { label: '机台', value: 'MACHINE' },
            { label: '打印机', value: 'PRINTER' }
          ]
        },
        {
          label: '设备品牌',
          prop: 'brand'
        },
        {
          label: '设备型号',
          prop: 'model'
        },
        {
          label: '设备规格',
          prop: 'specification'
        },
        {
          label: '所在车间',
          prop: 'workshopName'
        },
        {
          label: '所在产线',
          prop: 'lineName'
        },
        {
          label: '负责人员',
          prop: 'principalName'
        },
        {
          label: '状态',
          prop: 'status',
          search: true,
          type: 'select',
          dicUrl: '/api/blade-system/dict/dictionary?code=equipment_ledger_status',
          props: {
            label: 'dictValue',
            value: 'dictKey'
          }
        },
        {
          label: '备注',
          prop: 'remark'
        },
        {
          label: 'IP地址',
          prop: 'ip'
        },
        {
          label: '端口',
          prop: 'port'
        },
        {
          label: '主机名称',
          prop: 'hostName'
        },
        {
          label: '网络协议类型',
          prop: 'protocol'
        }
      ];
    }
  }
};
</script>
<style lang="scss" scoped>
.tranfer-dialog {
  ::v-deep .avue-crud__search {
    width: 100% !important;
    border: none !important;
  }
  ::v-deep .avue-crud__right {
    display: none !important;
  }
  ::v-deep .avue-crud__pagination {
    position: absolute;
    padding: 25px 0 50px 20px !important;
  }

  ::v-deep .el-dialog__footer {
    margin-top: 65px;
  }
}
.used-detail {
  ::v-deep .avue-crud__menu {
    display: none;
  }
}
</style>
